package UdpDit;

import java.io.IOException;
import java.net.*;
import java.util.HashMap;
import java.util.Map;

public class Server {
    Map<String, String> dict = new HashMap<>();

    private DatagramSocket socket = null;

    public Server() throws SocketException, UnknownHostException {
        socket = new DatagramSocket(9090, InetAddress.getByName("127.0.0.1"));

        dict.put("cat", "猫");
        dict.put("dog", "狗");
        dict.put("pig", "猪");

    }

    public void start() throws IOException {
        System.out.println("服务器启动");

        while (true){
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPacket);
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());

            String response = process(request);
            System.out.println(response);

            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);
        }
    }

    public String process(String request){
        return dict.getOrDefault(request, "没有查到该词");
    }

    public static void main(String[] args) throws IOException {
        Server server = new Server();
        server.start();
    }
}
